﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace DragDraw.Tool
{
    public partial class PhotoBoard : UserControl
    {
        private IPhotoPlayer m_player;

        public PhotoBoard()
        {
            InitializeComponent();
        }

        public void Init(IPhotoPlayer player)
        {
            m_player = player;
            Refresh();
        }

        void Refresh()
        {
            TxtUrl.Text = "";
            ListPhotos.ItemsSource = m_player.Photos.ToArray();
        }

        private void BtnNew_Click(object sender, RoutedEventArgs e)
        {
            Photo p = new Photo();
            m_player.Photos.Add(p);
            Refresh();
        }

        private void BtnDel_Click(object sender, RoutedEventArgs e)
        {
            if (ListPhotos.SelectedIndex > 0 &&
                m_player.Photos.Count >= ListPhotos.SelectedIndex)
            {
                m_player.Photos.RemoveAt(ListPhotos.SelectedIndex);
            }
            
            Refresh();
        }

        private void BtnUp_Click(object sender, RoutedEventArgs e)
        {

        }

        private void BtnDown_Click(object sender, RoutedEventArgs e)
        {

        }

        private void ListPhotos_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (ListPhotos.SelectedIndex >= 0)
            {
                BtnSave.Visibility = Visibility.Collapsed;
                TxtUrl.Text = m_player.Photos[ListPhotos.SelectedIndex].ImgUrl;
            }
        }

        private void TxtUrl_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(TxtUrl.Text) == false &&
                ListPhotos.SelectedItem != null &&
                TxtUrl.Text != m_player.Photos[ListPhotos.SelectedIndex].ImgUrl)
                BtnSave.Visibility = Visibility.Visible;
            else
                BtnSave.Visibility = Visibility.Collapsed;
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            if (ListPhotos.SelectedIndex >= 0)
            {
                m_player.Photos[ListPhotos.SelectedIndex].ImgUrl = TxtUrl.Text;
            }
            m_player.SavePhotos();
            Refresh();
            BtnSave.Visibility = Visibility.Collapsed;
        }
    }

    public interface IPhotoPlayer
    {
        void SavePhotos();
        List<Photo> Photos { get; set; }
    }
}
